﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenThesis.DTO.FX;

namespace OpenThesis.FX
{
	// Expose through an interface to allow interchangeable implementations (for testing etc)
	public interface IFactory
	{
		List<Position> BuildPositions(IList<Trade> activeTrades);
	}

	class Factory : IFactory
	{
		public List<Position> BuildPositions(IList<Trade> activeTrades)
		{
			List<Position> response = new List<Position>();
			// Note: use comparer instead of depending on the instance of the contract to be the same
			var contractsTraded = activeTrades.GroupBy(t => t.AcquiredPosition.Contract);

			foreach (var contract in contractsTraded)
			{
				var deliveriesTraded = contract.GroupBy(c => c.AcquiredPosition.SettlementDate);

				foreach (var delivery in deliveriesTraded)
				{
					decimal positionQuantity = 0;
					foreach (var trade in delivery)
					{
						positionQuantity += trade.AcquiredPosition.Quantity;
					}
					var accumulatedPosition = new Position(contract.Key, positionQuantity, delivery.Key);
					response.Add(accumulatedPosition);
				}
			}

			return response;
		}
	}
}
